package com.example.qasys.service;


import com.example.qasys.config.Result;
import com.example.qasys.entities.CodyRequest;
import com.example.qasys.utils.OkHttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class CodyService {

    @Resource
    OkHttpUtil okHttpUtil;

    @Resource
    CodySentAndGet sentAndGet;

    CodyRequest codyRequest = new CodyRequest();

    public Result postQuestionAndGetAnswer(String question) throws IOException, InterruptedException {
        question = "\""+question+"\"";

        Headers headers = codyRequest.getCodyRequestHead();
//        System.out.println(headers.toString());
        String requestBodyJson = "{\"content\":"+question+","+"\"conversation_id\":\"8729\"}";
//        System.out.println(requestBodyJson);
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, requestBodyJson);

//        System.out.println(CodyRequest.token);
//        System.out.println(CodyRequest.cookie);

        Request request = new Request.Builder()
                .url("https://getcody.ai/web/messages")
                .headers(headers)
                .post(requestBody)
                .build();
        String postRes = okHttpUtil.doPost(request);
        if(postRes.contains("CSRF token mismatch"))
            return new Result("token过期");
        Request re = new Request.Builder()
                .headers(headers)
                .url("https://getcody.ai/web/messages?conversation_id=8729&page=1&per_page=50&includes=contextDocuments,user")
                .build();
        String answer = okHttpUtil.doGet(re);
        ObjectMapper objectMapper = new ObjectMapper();
//        String answer =  response.body().string();
        JsonNode jsonNode = objectMapper.readTree(answer);
        List<String> content = jsonNode.findValuesAsText("content");
        while (content.get(0).equals(question.substring(1, question.length() - 1))){
           answer =okHttpUtil.doGet(re);
           jsonNode = objectMapper.readTree(answer);
           content = jsonNode.findValuesAsText("content");
           Thread.sleep(5000);
        }

//        System.out.println(question.substring(1, question.length() - 1));
        return new Result(true,content.get(0));
    }

    public Result setCookieAndToken(String cookie,String token){

        codyRequest.setCookieAndToken(cookie,token);
        return new Result(true);
    }

    public Result postQuestionAndGetAnswerNoToken(String question) throws IOException, InterruptedException {
        sentAndGet.sentMessage(question);
        String answer = sentAndGet.getAnswer();

        ObjectMapper objectMapper = new ObjectMapper();
//        System.out.println(answer);
//        String answer =  response.body().string();
        JsonNode jsonNode = objectMapper.readTree(answer);
        List<String> content = jsonNode.findValuesAsText("content");
//        System.out.println(question);
//        System.out.println(content.get(0));
        while (content.get(0).equals(question)){
            answer = sentAndGet.getAnswer();
            jsonNode = objectMapper.readTree(answer);
            content = jsonNode.findValuesAsText("content");
            Thread.sleep(500);
        }
        return new Result(true,content.get(0).replace("<br />",""));
    }

    public Result uploadTxt(File file) throws IOException {
        String url = "https://getcody.ai/web/file-imports/uploaded?includes=file";
        String directoryId = "8838";

        String key = "tmp/b20e7253-39dd-46df-88c0-9747790c1663";
        String fileType = "text/plain";

        // Create OkHttp client
        OkHttpClient client = new OkHttpClient();

        // Create request body
        String fileName = file.getName();

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("directory_id", directoryId)
                .addFormDataPart("key", key)
                .addFormDataPart("type", fileType)
                .addFormDataPart("name", fileName)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse(fileType), file))
                .build();


        // Create request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("X-XSRF-TOKEN", CodyRequest.token)
                .addHeader("Cookie", CodyRequest.cookie)
                .post(requestBody)
                .build();

        // Execute request
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            String responseBody = response.body().string();
            if (responseBody.contains("id")){
                return new Result(true,"上传成功");
            }


//            System.out.println(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(false);
    }


    public Result uploadWord(File file) throws IOException {
        String url = "https://getcody.ai/web/file-imports/uploaded?includes=file";
        String directoryId = "8838";

        String key = "tmp/b20e7253-39dd-46df-88c0-9747790c1663";
        String fileType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

        // Create OkHttp client
        OkHttpClient client = new OkHttpClient();

        // Create request body
        String fileName = file.getName();
        System.out.println(file.length());


        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("directory_id", directoryId)
                .addFormDataPart("key", key)
                .addFormDataPart("type", fileType)
                .addFormDataPart("name", fileName)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse(fileType), file))
                .build();

        System.out.println(requestBody.contentLength());
        // Create request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("X-XSRF-TOKEN", CodyRequest.token)
                .addHeader("Cookie", CodyRequest.cookie)
                .post(requestBody)
                .build();

        // Execute request
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            String responseBody = response.body().string();
            if (responseBody.contains("id")){
                return new Result(true,"上传成功");
            }


//            System.out.println(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(false);
    }


}
